"use client"

import { useEffect } from "react"
import { Lock } from "@/types/admin"
import { useAdminStore } from "@/lib/store"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"

const formSchema = z.object({
  name: z.string().min(1, "名称不能为空"),
  department: z.string().min(1, "部门不能为空"),
  keyId: z.string().min(1, "钥匙ID不能为空"),
  status: z.enum(["locked", "unlocked", "faulty", "maintenance"]),
})

type FormValues = z.infer<typeof formSchema>

interface LockDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  lock?: Lock
}

const statusOptions = [
  { value: "locked", label: "已上锁" },
  { value: "unlocked", label: "未上锁" },
  { value: "faulty", label: "故障" },
  { value: "maintenance", label: "维修中" },
];

export function LockDialog({
  open,
  onOpenChange,
  lock,
}: LockDialogProps) {
  const { departments, addLock, updateLock } = useAdminStore()
  const isEditing = !!lock

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      department: "",
      keyId: "",
      status: "locked",
    },
  })

  useEffect(() => {
    if (open) {
      if (lock) {
        form.reset(lock)
      } else {
        form.reset({
          name: "",
          department: "",
          keyId: "",
          status: "locked",
        })
      }
    }
  }, [open, lock, form])

  const onSubmit = (values: FormValues) => {
    const lockData = {
      ...values,
      lastOperationTime: new Date().toLocaleString("zh-CN"),
    }

    if (isEditing && lock) {
      updateLock(lock.id, lockData)
    } else {
      addLock({ ...lockData, id: `lock-${Date.now()}` })
    }

    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{isEditing ? "编辑锁具" : "新增锁具"}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? "修改锁具信息，点击保存确认更改。"
              : "添加新锁具，填写信息后点击创建。"}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>名称</FormLabel>
                  <FormControl>
                    <Input placeholder="例如：电子锁A" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="department"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>部门</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="选择一个部门" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {departments.map(dept => (
                        <SelectItem key={dept.id} value={dept.name}>
                          {dept.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="keyId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>钥匙ID</FormLabel>
                  <FormControl>
                    <Input placeholder="例如：key-101" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>状态</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="选择状态" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {statusOptions.map(option => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <Button type="submit">{isEditing ? "保存" : "创建"}</Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 